﻿using System.Threading.Tasks;
using Xproject.Framework.Core;
using Xproject.Framework.Core.DataContext;
using Xproject.Framework.Core.Repositories;
using Model.WXshopBuiness;
using Model.WXshopBuiness.Enum;
using Repository.WXshopBuiness;
using Repository.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Model.Const;
using Model.Util;
using Model.WXshopBuiness.DTO;

namespace Services.WXshopBuiness
{
    /// <summary>
    /// 活动服务
    /// </summary>
   public  class PromotionServices:Service
    {
        IRepositoryAsync<PromotionsKanJiaDetail> m_PromotionsKJDetailRepository;
        IRepositoryAsync<Promotions> m_PromotionsRepository;
        IRepositoryAsync<UserProductKanJia> m_UserProductKJRepository;
        IRepositoryAsync<WeiXinOrder> m_WeiXinOrderRepository;
        IRepositoryAsync<ShoppingCar> m_ShoppingCarRepository;
        WXOrderServices m_WXOrderServices;
        public PromotionServices(IDataContextAsync dataContext, WXOrderServices mWXOrderServices) : base(dataContext)
        {
            m_PromotionsRepository = m_UnitOfWork.RepositoryAsync<Promotions>();
            m_PromotionsKJDetailRepository = m_UnitOfWork.RepositoryAsync<PromotionsKanJiaDetail>();
            m_UserProductKJRepository = m_UnitOfWork.RepositoryAsync<UserProductKanJia>();
            m_WeiXinOrderRepository = m_UnitOfWork.RepositoryAsync<WeiXinOrder>();
            m_ShoppingCarRepository = m_UnitOfWork.RepositoryAsync<ShoppingCar>();
            m_WXOrderServices = mWXOrderServices;
        }

        public UserProductKanJia GetUserProductKJbyID(string KanJiaID)
        {
            return m_UserProductKJRepository.GetById(KanJiaID);             
        }

        public UserProductKanJia CheckUserHasCreatedThisProductKanJia(string PromotionID, string  ProductID, string userId,string orderId)
        {           
          return m_UserProductKJRepository.GetBy(userId,  ProductID,  PromotionID,orderId,0);           
        }


        public List<Promotions> GetAllPromotions()
        {
            return m_PromotionsRepository.GetPromotionsList(null, null, null, null, 0);
        }

        public List<Promotions> GetPromotionList(int offset, int limit, string promotionName, DateTime? startTime, DateTime? endTime, string PromotionUnidName,int? disable,out int total)
        {
            total = 0;
            List<Promotions> list = m_PromotionsRepository.GetPromotionsList(promotionName,startTime,endTime,PromotionUnidName,disable);
            if (list != null && list.Count > 0)
            {
                total = list.Count;
            }
            total = list.Count;
            return list.Skip(offset).Take(limit).ToList();            
        }

        public int AddProductKanJiaFromShopCar(WeiXinOrder order, Promotions promotions, WXProduct product, string userId, string userName, string remark, string KanJiaDesc
            , decimal useScore, decimal useCash, decimal useBalance, decimal useCoupon, int platform, out string message, out string kanjiaId)
        {
            message = string.Empty;
            kanjiaId = string.Empty;
            if (promotions == null)
            {
                message = "没有此活动，活动不存在或者已下架";
                return 0;
            }
            //新增一个用户 --产品 --砍价 数据
            UserProductKanJia UPKJ = new UserProductKanJia();
            UPKJ.AleradKanJiaMoney = 0.00M;
            UPKJ.AlreadKanJiaCount = 0;
            UPKJ.CreateTime = DateTime.Now;
            UPKJ.DeadLineTime = promotions.EndTime;
            //to do 
            UPKJ.EachKanJiaMaxMoney = decimal.Parse(promotions.Param1);
            UPKJ.EntityState = EntityState.Added;
            UPKJ.IsUsed = 0;
            UPKJ.KanJiaDesc = KanJiaDesc;
            kanjiaId = UPKJ.KanJiaID = Guid.NewGuid().ToString();
            UPKJ.MaxKanJiaCount = int.Parse(promotions.Param2);
            UPKJ.MaxKanJiaMoney = product.SalePrice * decimal.Parse(promotions.Param3);
            UPKJ.OrderId = order.OrderID;
            UPKJ.ProductID = product.ProductID;
            UPKJ.PromotionID = promotions.PromotionID;
            UPKJ.UserID = userId;
            UPKJ.UserName = userName;
            m_UnitOfWork.BeginTransaction();
            order.PromotionID = promotions.PromotionID;
            order.EntityState = EntityState.Modified;
            m_WeiXinOrderRepository.Update(order);
            m_UserProductKJRepository.Insert(UPKJ);
            if (m_UnitOfWork.SaveChanges() == 2)
            {
                m_UnitOfWork.Commit();
                return 1;
            }
            else
            {
                m_UnitOfWork.Rollback();
                message = "系统似乎有点点小问题。请联系客服";
                m_UnitOfWork.Rollback();
                return 0;
            }
        }

        public int AddProductKanJia(string orderId,Promotions promotions, WXProduct product, string orderName, string userId,string userName, string remark,string KanJiaDesc
            , decimal useScore, decimal useCash, decimal useBalance, decimal useCoupon, int platform,out string message,out string kanjiaId)
        {
            message = string.Empty;
            kanjiaId = string.Empty;
            if (promotions == null)
            {
                message = "没有此活动，活动不存在或者已下架";
                return 0;
            }
            WeiXinOrder order = new WeiXinOrder();
            order.OrderID = orderId;
            order.UserID = userId;
            order.OrderCode = m_WXOrderServices.CreateOrderCode("O",product.ProductID);
            order.OrderMoney = product.SalePrice;
            order.CreateTime = DateTime.Now;
            order.OrderSource = (int)Enum_OrderSource.WXSHOP;
            order.PayType = (int)Enum_PayType.WEIXIN;
            order.OrderState = (int)Enum_OrderState.WAITINGPAY;
            order.Remark = remark;
            order.UseScore = useScore;
            order.UseCash = useCash;
            order.UseBalance = useBalance;
            order.UseCoupon = useCoupon;
            order.Platform = platform;
            order.ProductId = product.ProductID;
            order.OrderName = orderName;
            order.ProductNum = 1;
            order.ThatTimeSalePrice = product.SalePrice;
            order.PromotionID = product.PromotionId;//一定要订单里存砍价活动，因为产品可能会变更活动，原来的订单得保持原来的活动规则
            order.EntityState = EntityState.Added;
            //还需要增加一个shopcar 记录 因为默认方式是先购物车，然后支付，直接生产订单的没有购物车信息，所以默认造一个
            ShoppingCar sc = new ShoppingCar();
            sc.ShopCarId = Guid.NewGuid().ToString();
            sc.CreateTime = sc.UpdateTime = DateTime.Now;
            sc.EntityState = EntityState.Added;
            sc.ItemState = 1;//默认使用过
            sc.ProductDesc = product.ShortDesc;
            sc.ProductId = product.ProductID;
            sc.ProductImgUrl = product.Domain+product.ThumbnailUrl1;
            sc.ProductName = product.ProductName;
            sc.ProductNum = 1;
            sc.ProductSpecificationId = "";//如果产品有speci规格，不同规格参加活动，还没设计，默认只有单一产品参加活动
            sc.ProductSpecificationName = "";
            sc.ProductUrl = product.Domain+"/Shop/ProductDetail?productId=" + product.ProductID;
            sc.Remarks = "从产品页面直接砍价方式加入购物车，并使用";
            sc.SingleOrigPrice = product.MarketPrice;
            sc.SinglePrice = product.SalePrice;
            sc.UserId = userId;
            order.ShopCarId = sc.ShopCarId;
            m_UnitOfWork.BeginTransaction();
            m_WeiXinOrderRepository.Insert(order);
            m_ShoppingCarRepository.Insert(sc);
            //新增一个用户 --产品 --砍价 数据
            UserProductKanJia UPKJ = new UserProductKanJia();
            UPKJ.AleradKanJiaMoney = 0.00M;
            UPKJ.AlreadKanJiaCount = 0;
            UPKJ.CreateTime = DateTime.Now;
            UPKJ.DeadLineTime = promotions.EndTime;
            //to do 
            UPKJ.EachKanJiaMaxMoney =decimal.Parse( promotions.Param1);
            UPKJ.EntityState = EntityState.Added;
            UPKJ.IsUsed = 0;
            UPKJ.KanJiaDesc = KanJiaDesc;
            kanjiaId= UPKJ.KanJiaID = Guid.NewGuid().ToString();
            UPKJ.MaxKanJiaCount = int.Parse(promotions.Param2);
            UPKJ.MaxKanJiaMoney = product.SalePrice * decimal.Parse(promotions.Param3);
            UPKJ.OrderId = order.OrderID;
            UPKJ.ProductID = product.ProductID;
            UPKJ.PromotionID = promotions.PromotionID;
            UPKJ.UserID = userId;
            UPKJ.UserName = userName;
            m_UserProductKJRepository.Insert(UPKJ);
            if (m_UnitOfWork.SaveChanges() == 3)
            {
                m_UnitOfWork.Commit();
                return 1;
            }
            else {
                message = "系统似乎有点点小问题。请联系客服";
                m_UnitOfWork.Rollback();
                return 0;
            }             
        }

        public int DoAnKanJia(UserProductKanJia kjinfo, string UserId, string UserName,out decimal rmoney,out string message)
        {  
            rmoney = 0.00M;
            message = string.Empty;
            //先检测对于这个砍价 是否已经砍过
            PromotionsKanJiaDetail detail =  m_PromotionsKJDetailRepository.GetByIdAndUserId(kjinfo.KanJiaID, UserId);
            if (detail != null)
            {
                message = "您已帮TA砍过价辣，朋友说爱死你啦！";
                return 3;
            }
            else
            {
                //随机一个砍价money
                Random rd = new Random();                        
                  rmoney = kjinfo.EachKanJiaMaxMoney * decimal.Parse( rd.NextDouble().ToString());
                decimal canKJmoney = kjinfo.MaxKanJiaMoney - kjinfo.AleradKanJiaMoney;
                if (kjinfo.AleradKanJiaMoney == 0.00M) //第一次砍价
                {
                    decimal systemFirstSendMoney = 0.00M;
                     Promotions p= m_PromotionsRepository.GetById(kjinfo.PromotionID);
                    if (!string.IsNullOrEmpty(p.Param4)&&p.Param4!="null")
                    {
                        decimal.TryParse(p.Param4, out systemFirstSendMoney);
                        rmoney = rmoney + systemFirstSendMoney;
                    }
                }
                if (rmoney > canKJmoney)
                {
                    rmoney = canKJmoney;
                }
                PromotionsKanJiaDetail newone = new PromotionsKanJiaDetail();
                newone.CreateTime = DateTime.Now;
                newone.EntityState = EntityState.Added;
                newone.ID = Guid.NewGuid().ToString();
                newone.KanJiaID = kjinfo.KanJiaID;
                newone.KanJiaMoney = rmoney;
                newone.UserID = UserId;
                newone.UserName = UserName;
                m_UnitOfWork.BeginTransaction();
                m_PromotionsKJDetailRepository.Insert(newone);
                kjinfo.AlreadKanJiaCount = kjinfo.AlreadKanJiaCount+1;
                kjinfo.AleradKanJiaMoney = kjinfo.AleradKanJiaMoney + rmoney;
                kjinfo.EntityState = EntityState.Modified;
                m_UserProductKJRepository.Update(kjinfo);
                int result =   m_UnitOfWork.SaveChanges();
                if (result == 2)
                {
                    m_UnitOfWork.Commit();
                    message = "帮忙砍价成功！";
                    return 1;
                }
                else
                {
                    message = "帮忙砍价失败";
                    m_UnitOfWork.Rollback();
                    return 0;
                }

                //新增一个砍价
            }

        }

        public List<PromotionsKanJiaDetail> GetKJdetailList(string KanJiaId)
        {
            return m_PromotionsKJDetailRepository.GetKJDetailList(KanJiaId);
        }


        public UserProductKanJia GetUserProdKJByOrder(string orderId)
        {
          return  m_UserProductKJRepository.GetBy(orderId);
        }

        public bool UpdateUserProdKJToUsed(UserProductKanJia upkj)
        {
            upkj.EntityState = EntityState.Modified;
            upkj.IsUsed = 1;
            m_UserProductKJRepository.Update(upkj);
            return m_UnitOfWork.SaveChanges() == 1;
        }

        public bool AddPromotions(Promotions promotions)
        {
            promotions.EntityState = EntityState.Added;
            m_PromotionsRepository.Insert(promotions);
            return m_UnitOfWork.SaveChanges() == 1;
        }

        public bool EditPromotions(Promotions promotions)
        {
            promotions.EntityState = EntityState.Modified;
            m_PromotionsRepository.Update(promotions);
            return m_UnitOfWork.SaveChanges() == 1;
        }

        public bool DelPromotions(Promotions promotions)
        {
            promotions.EntityState = EntityState.Deleted;
            m_PromotionsRepository.Delete(promotions);
            return m_UnitOfWork.SaveChanges() == 1;
        }

        public bool UpdateUserProductKanJiaState(UserProductKanJia upkj,int isused)
        {
            upkj.EntityState = EntityState.Modified;
            upkj.IsUsed = isused;
            m_UserProductKJRepository.Update(upkj);
            return m_UnitOfWork.SaveChanges() == 1;
        }
        public Promotions GetPromotionsById(string PromotionId)
        {
            return m_PromotionsRepository.GetById(PromotionId);
        }
        public Promotions GetPromotionsByUnidName(string unidName)
        {
            return m_PromotionsRepository.GetPromotionsByUnidName(unidName);
        }
    }
}
